/*
* 资源管理
*/
import React from 'react';
import BreadcrumbCustom from '../BreadcrumbCustom';
import { Row,Button,Modal,Input,message,Form} from 'antd';
import qs from 'qs';

import * as Request from '../../Server/SystemManger';
import WrappedUserForms from "./UserForms";
import {AuthA,AuthButton} from '../auth/OperationAuth';
import TablePage from "../TablePage";
import * as Constant from '../../common/const';
require('./customer.css');

const confirm = Modal.confirm;
const defaultPage = {page:Constant.DEFAULT_PAGE,size:Constant.DEFAULT_PAGE_SIZE};
const FormItem = Form.Item;


class UserManager extends  React.Component{
    constructor(props) {
        super(props);
        this.state = {
            userId:'',
            visible: false,
            title:undefined,
            id:undefined,
            disable:false,
            data : [],
            pagination:{},
            loading:true,
            searchKey:null,
            default:{}
        };
    }
    componentDidMount() {
        this.fetch();
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }

    fetch = (params = defaultPage) => {
        this.setState({loading:true});
        let paramStr = qs.stringify(params);
        Request.getUserPaging(paramStr).then(res =>{
            if(res && Constant.REQUEST_SUCCESS == res.code){
                let data = res.data;
                this.setState({
                    data:[...data.content.map(val => {
                        val.key = val.id;
                        return val;
                    })],
                    pagination:Object.assign(this.state.pagination,{total:data.totalSize,current:data.page + 1,pageSize:params.size}),
                    loading:false,
                });
            }
        })
    }
    /*
    *添加
    */
    add = () => {
        this.setState({
            visible: true,
            title:'添加用户',
            id:undefined,
            disable:false,
        });
    }
    /*查看*/
    detail = (id) =>{
        this.setState({
            id: id,
            disable:true,
            title:'查看用户',
            visible: true,
        });
    }
    /*编辑*/
    edit = (id) => {
        this.setState({
            id: id,
            disable:false,
            title:'编辑用户',
            visible: true,
        });
    }
    showConfirm = (id,roleNameList,username) => {
        let roleArr = [];
        roleNameList.map(obj => roleArr.push(obj.name))
        if('admin'==username){
            message.error("超级管理员账号不能删除!")
        }else{
            confirm({
                title: '删除提示',
                content: '确认删除该用户吗？',
                maskClosable: true,
                okText: '确定',
                okType:'primary',
                cancelText: '取消',
                onOk:this.delete.bind(this,id)
            });
        }
    }
    /*删除*/
    delete = (id) =>{
       Request.deleteUserById(id).then(res => {
            if(res && Constant.REQUEST_SUCCESS == res.code){
                message.success('用户删除成功!');
                this.fetch(this.getPageParams(true));
            }
       })
    }

    search = () => {
        const name = this.props.form.getFieldValue('name');
        this.setState({
            searchKey: name,
            loading:true
        });
        this.fetch({page:Constant.DEFAULT_PAGE,size:this.currentPageSize(),username:name});
    }
    reset = () => {
        this.setState({
            searchKey: undefined,
            loading:true
        });
        this.props.form.setFieldsValue({name:undefined});
        this.fetch({page:Constant.DEFAULT_PAGE,size:this.currentPageSize()});
    }
    /*
    * 取消
    */
    cancel = (flag=false) => {
        typeof flag == 'object' && (flag=false);
        this.setState({
            visible: false,
        });
        flag && this.fetch(this.getPageParams());
    }

     /* 翻页 */
     handleTableChange = (pagination) => {
        const _this = this;
        const pager = { ..._this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        _this.setState({
            pagination: pager,
            loading:true
        });
        _this.fetch(this.getPageParams(false,pagination));
    }

    getPageParams = (isDelete = false,pagination = this.state.pagination) => {
         const params = {
             page: pagination.current -1 ,//后台分页默认从第0页开始
             size: pagination.pageSize,
             username:this.state.searchKey
         };
         //若当前页只有一条数据,并且不是第一页,删除后,展示前一页的数据
         if(isDelete && pagination.current == Math.ceil(pagination.total/pagination.defaultPageSize)
         && pagination.total%pagination.defaultPageSize == 1){
             params.page > 0 && params.page --;
         }
         return params;
    }

    currentPageSize = () => this.state.pagination.pageSize || Constant.DEFAULT_PAGE_SIZE;
    render(){
        const {getFieldDecorator} = this.props.form;
        const columns = [
            {
                "title": 'ID', 
                "align":'center',
                "dataIndex":'id',
                'width':'16.66%'
            },
            {
                "title": '用户名', 
                "align":'center',
                "dataIndex":'username',
                'width':'16.66%'
            },
            {
                "title": '状态', 
                "align":'center',
                "dataIndex":'status',
                'width':'16.66%',
                render:(text) => text ? '启用' : '禁用',
            },
            {
                "title": '角色', 
                "align":'center',
                "dataIndex":"roleList",
                'width':'16.66%',
                render:(text,record) => {
                    let values = []
                    text.map(val => values.push(val['name']))
                    return <span>{values.join(',')}</span>
                }
            },
            {
                "title": '分部', 
                "align":'center',
                "dataIndex":'sysCompany.name',
                'width':'16.66%',
            },
            {
                "title": "操作", 
                "align":'center',
                "key":"action",
                'width':'16.66%',
                render:(text, record) => (
                    <span>
                        <AuthA className={'operation-primary'} onClick={this.detail.bind(this,record.id)} permission={'user:get'}>
                            查看
                        </AuthA>
                        <AuthA disabled={record.id==1} className={'operation-primary'} onClick={this.edit.bind(this,record.id)} permission={'user:save'}>
                            编辑
                        </AuthA>
                        <AuthA disabled={record.id==1} onClick={this.showConfirm.bind(this,record.id,text.roleList, record.username)} className={'operation-danger'} permission={'user:delete'}>
                            删除
                        </AuthA>
                    </span>
                )
            }
        ]

        return (
            <div>
                <BreadcrumbCustom  first={"用户管理"}/>
                <Row>
                    <Form  layout="inline" onSubmit={this.search}>
                        <FormItem  label={'用户名:'}>
                            {getFieldDecorator('name',{
                                initialValue:this.state.RoleManagers,
                            })(
                                <Input maxLength={255}/>
                            )}
                        </FormItem>
                        <FormItem >
                            <Button
                                type="primary"
                                htmlType="submit"
                            >查询</Button>
                            <Button
                                type="default"
                                onClick={this.reset}
                            >重置</Button>
                        </FormItem>
                    </Form>
                </Row>
                <Row span={2} className="button-margin">
                    <AuthButton  size={'large'} onClick={this.add.bind(this,'添加用户')} permission={'user:save'}>
                        添加用户
                    </AuthButton>
                </Row>
                <TablePage
                    dataSource={this.state.data} 
                    columns ={columns} 
                    loading={this.state.loading} 
                    pagination={this.state.pagination}
                    onChange={this.handleTableChange}
                />
                <Modal
                    title={this.state.title}
                    visible={this.state.visible}
                    footer={null}
                    onCancel={this.cancel}
                    maskClosable={false}
                    destroyOnClose={true}
                    centered={true}
                >
                    <WrappedUserForms id={this.state.id} disable={this.state.disable} cancel={this.cancel}/>
                </Modal>
            </div>
        )
    }
}

const UserManagerForm = Form.create()(UserManager);
export default UserManagerForm;